/**
 * Author xiaol
 * Rev
 * Date: 2021-03-26 20:14
 * <p>
 * Copyright (C) 2021 Seeyon, Inc. All rights reserved.
 * <p>
 * This software is the proprietary information of Seeyon, Inc.
 * Use is subject to license terms.
 * @company seeyon.com
 * @author xiaol
 */
package com.lagou.proxy;

import com.lagou.annotate.Transactional;
import com.lagou.datasource.DataSourceConfig;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

/**
 * @description
 * @date 2021-03-26 20:14
 * @author xiaol
 */
public class ProxyFactory<T> {


	public static<T> T createProxy(T obj){
		Object o = Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new InvocationHandler() {
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				if(method.isAnnotationPresent(Transactional.class)){
					Connection connection = DataSourceConfig.getConnection();
					DataSourceConfig.setConnection(connection);
					Object result = null;
					try {
						result = method.invoke(obj, args);
					}catch (Exception e){
						connection.rollback();
					}
					return result;
				};
				return method.invoke(obj, args);
			}
		});
		return (T) o;
	}
}
